package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author Lff
 * @date 2022/2/27
 */
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 分页查询
     * @param page     页码
     * @param pageSize 数据数量
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize) {
        Page<Category> pages = categoryService.findAllByPage(page, pageSize);
        return R.success(pages);
    }

    /**
     * 添加分类
     *
     * @param category
     * @return
     */
    @PostMapping
    @CacheEvict(value = "commonCache",key = "'categoryList'")
    public R<String> save(@RequestBody Category category) {
        boolean flag = categoryService.addCategory(category);
        if (flag) {
            return R.success("添加分类成功！");
        }
        return R.error("添加分类失败！");
    }

    /**
     * 删除代码
     * @param id
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = "commonCache",key = "'categoryList'")
    public R<String> del(Long id) {
        categoryService.delById(id);
        return R.success("删除成功！");
    }

    /**
     * 修改 Category
     * @param category
     * @return
     */
    @PutMapping()
    @CacheEvict(value = "commonCache",key = "'categoryList'")
    public R<String> upCategory(@RequestBody Category category){
        categoryService.updateCategory(category);
        return R.success("修改成功！");
    }

        /**
         * 获取所有的指定类型的分类信息
         * @param category
         * @return
         */
        @GetMapping("/list")
        @Cacheable(value = "commonCache",key = "'categoryList'")
        public R<List> getAllCategoryName(Category category){
            List<Category> categories = categoryService.getCategoryList(category);
            return R.success(categories);
        }
}
